<script lang="ts" setup>
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { StepTaskModel } from '#/api/process/models';

import { ref } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';

import { Button, message, Popconfirm } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  createStepTaskApi,
  deleteStepTaskApi,
  getStepTaskListApi,
  updateStepTaskApi,
} from '#/api/process/stepTask';

const stepId = ref(0);
const dataList = ref<StepTaskModel[]>([]);
const todoCount = ref(0);

const gridOptions: VxeGridProps<StepTaskModel> = {
  columns: [
    { type: 'seq', width: 60 },
    {
      field: 'taskCode',
      title: '工步代码',
      width: 140,
      editRender: { name: 'input' },
    },
    {
      field: 'taskName',
      title: '工步名称',
      minWidth: 140,
      editRender: { name: 'input' },
    },
    { field: 'seq', title: '顺序号', width: 60 },
    {
      field: 'standardTime',
      title: '作业时长(s)',
      width: 120,
      editRender: { name: 'input', attrs: { type: 'number' } },
    },
    {
      field: 'action',
      title: '操作',
      fixed: 'right',
      width: 160,
      slots: { default: 'action' },
    },
  ],
  data: dataList.value,
  border: true,
  keepSource: true,
  stripe: true,
  editConfig: {
    mode: 'row',
    trigger: 'manual',
    showStatus: true,
    autoClear: false,
  },
  editRules: {
    taskCode: [{ required: true, message: '必须填写' }],
    taskName: [{ required: true, message: '必须填写' }],
  },
  pagerConfig: {
    enabled: false,
  },
};

const [Grid, gridApi] = useVbenVxeGrid({ gridOptions });

const [Drawer, drawerApi] = useVbenDrawer({
  onCancel() {
    drawerApi.close();
  },
  onConfirm: () => {
    drawerApi.close();
  },
  onOpenChange: async (isOpen: boolean) => {
    if (isOpen) {
      const input = drawerApi.getData<Record<string, any>>();
      drawerApi.setState({ title: `工步设置 [${input.opName}]` });

      // 加载数据
      stepId.value = input.stepId;
      todoCount.value = 0;
      await loadData();
    }
  },
  title: '工步设置',
  showCancelButton: false,
  showConfirmButton: false,
});

/** 加载数据 */
async function loadData() {
  dataList.value.length = 0; // 清空数组
  const data = await getStepTaskListApi(stepId.value);
  dataList.value.push(...data);
}

function addRow() {
  // 校验是否有为进行保存的行
  if (todoCount.value > 0) {
    message.warning(`请先保存当前新增的行`);
    return;
  }

  ++todoCount.value;
  const item: StepTaskModel = {
    id: 0,
    stepId: stepId.value,
    taskCode: '',
    taskName: '',
    seq: dataList.value.length + 1,
    standardTime: 0,
    isCheckStandard: false,
  };
  // gridApi.grid.insertAt(item, -1);
  dataList.value.push(item);
  gridApi.grid.setEditRow(item);
}

function cancelRow(row: StepTaskModel) {
  gridApi.grid.clearEdit();
  // 恢复到初始状态
  // bug: 更改数据提交保存后，再取消时数据回滚到了最初始状态
  gridApi.grid.revertData(row);
}

async function saveRow(row: StepTaskModel) {
  await gridApi.grid?.clearEdit();
  if (await gridApi.grid.validate(row)) {
    message.success(`校验不通过！`);
    return;
  }

  // 更新
  if (row.id > 0) {
    const ok = await updateStepTaskApi(row);
    if (ok) {
      message.success(`更新成功，工步：${row.taskName}`);
    }
    return;
  }

  // 新增
  gridApi.setLoading(true);
  const ok2 = await createStepTaskApi(row);
  if (ok2) {
    message.success(`新增成功，工步：${row.taskName}`);
    await loadData();
    --todoCount.value;
  }
  gridApi.setLoading(false);
}

async function deleteRow(row: StepTaskModel) {
  if (row.id > 0) {
    if (await deleteStepTaskApi(row.id)) {
      message.success(`删除成功，工步：${row.taskName}`);
      await loadData();
    }
  } else {
    // 直接删除
    dataList.value.splice(
      dataList.value.findIndex((item) => item.id === row.id),
      1,
    );
    --todoCount.value;
  }
}
</script>

<template>
  <Drawer>
    <div class="h-full">
      <Grid>
        <template #toolbar-actions>
          <Button size="small" @click="addRow()">新增</Button>
        </template>
        <template #action="{ row }">
          <template v-if="gridApi.grid.isEditByRow(row)">
            <Button size="small" type="link" @click="saveRow(row)">
              保存
            </Button>
            <Button size="small" type="link" @click="cancelRow(row)">
              取消
            </Button>
          </template>
          <template v-else>
            <Button
              size="small"
              type="link"
              @click="gridApi.grid.setEditRow(row)"
            >
              编辑
            </Button>
          </template>
          <Popconfirm title="确定要删除吗？" @confirm="deleteRow(row)">
            <Button danger size="small" type="link"> 删除 </Button>
          </Popconfirm>
        </template>
      </Grid>
    </div>
  </Drawer>
</template>
